import { NextResponse } from 'next/server'
import { promises as fs } from 'fs'
import path from 'path'

/**
 * GET /api/download/[...path] - 下载本地存储的文件
 * 支持需求 1.5 - 应用文件下载
 */
export async function GET(request, { params }) {
    try {
        const resolvedParams = await params
        const filePath = resolvedParams.path.join('/')

        // 安全检查：只允许下载 uploads 目录下的文件
        if (!filePath.startsWith('uploads/')) {
            return NextResponse.json({
                success: false,
                error: {
                    code: 'INVALID_PATH',
                    message: '无效的文件路径'
                }
            }, { status: 400 })
        }

        // 构建完整的文件路径
        const fullPath = path.join(process.cwd(), 'public', filePath)

        // 检查文件是否存在
        try {
            await fs.access(fullPath)
        } catch (error) {
            return NextResponse.json({
                success: false,
                error: {
                    code: 'FILE_NOT_FOUND',
                    message: '文件不存在'
                }
            }, { status: 404 })
        }

        // 读取文件
        const fileBuffer = await fs.readFile(fullPath)

        // 获取文件名
        const fileName = path.basename(filePath)

        // 设置响应头
        const headers = new Headers()
        headers.set('Content-Disposition', `attachment; filename="${fileName}"`)
        headers.set('Content-Type', 'application/octet-stream')
        headers.set('Content-Length', fileBuffer.length.toString())

        return new NextResponse(fileBuffer, {
            status: 200,
            headers
        })

    } catch (error) {
        console.error('文件下载失败:', error)

        return NextResponse.json({
            success: false,
            error: {
                code: 'DOWNLOAD_FAILED',
                message: '文件下载失败',
                details: process.env.NODE_ENV === 'development' ? error.message : undefined
            }
        }, { status: 500 })
    }
}